package com.example.demo.demos;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Controller
public class FileController {
    public static final String UPLOAD_DIR=System.getProperty("user.dir")+"/uploads/";
    @GetMapping("/")
    public String index(){
        return "index";
    }
    @PostMapping("/upload")
    public String UpLoad(@RequestParam("file")MultipartFile file, Model model){
        try {
            String  fileName = UUID.randomUUID().toString()+"_"+file.getOriginalFilename();
            Path filepath = Paths.get(UPLOAD_DIR,fileName);
            Files.createDirectories(filepath.getParent());
            Files.copy(file.getInputStream(),filepath);
            model.addAttribute("message","文件上传成功！");
        } catch (IOException e) {
            model.addAttribute("message","文件上传失败！");
            e.printStackTrace();
        }
        return "index";
    }
    @GetMapping("/download/{fileName}")
    public ResponseEntity<Resource> DownLoad(@PathVariable String fileName){
        try {
            Path filepath = Paths.get(UPLOAD_DIR,fileName);
            Resource resource = new FileSystemResource(filepath.toFile());

            if (resource.exists()){
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\""+ filepath.toFile().getName() + "\"")
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }
}
